/*
 * frmVentanaAcceso.java
 *
 * Created on 23 de mayo de 2010, 01:15 AM
 */

package GUI.Principal;
import BusinessLogic.AccesoSistemaBL;
import BusinessLogic.ModuloBL;
import BusinessEntity.AccesoSistemaBE;
import BusinessEntity.LogUsuarioBE;
import BusinessEntity.UsuarioBE;
import BusinessEntity.ModuloBE;
import BusinessLogic.LogUsuarioBL;
import DataAccess.UsuarioDA;
import Seguridad.*;
import com.birosoft.liquid.LiquidLookAndFeel;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.UIManager;
import java.awt.*;


/**
 *
 * @author  tRufA
 */

public class frmVentanaAcceso extends javax.swing.JFrame {
    private int intentos = 0;
    private Encriptador objEncriptador=new Encriptador();
    private boolean conectado = false;
    private String nueva_contraseña;
    private String correo_destino;
    private String usr;
    private String nueva_contrasenha;
    
    /* Crea un nuevo formulario frmVentanaAcceso */
    public frmVentanaAcceso() {
        initComponents();
        Dimension dim = getToolkit().getScreenSize();
        Rectangle abounds = getBounds();
        this.setLocation((dim.width - abounds.width) / 2, (dim.height - abounds.height) / 2);
        //this.setBounds(450, 320, 293, 170);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnSalir = new javax.swing.JButton();
        btnRestablecerContrasena = new javax.swing.JButton();
        btnIngresar = new javax.swing.JButton();
        txtPassword = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        lblUsuario = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("BeOriginal");
        setBounds(new java.awt.Rectangle(600, 350, 293, 146));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMinimumSize(new java.awt.Dimension(120, 120));
        setName("frmVentanaAcceso"); // NOI18N
        setResizable(false);

        btnSalir.setText("Salir");
        btnSalir.setName("btnSalir"); // NOI18N
        btnSalir.setPreferredSize(new java.awt.Dimension(120, 40));
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnRestablecerContrasena.setText("Restablecer Contraseña");
        btnRestablecerContrasena.setToolTipText("");
        btnRestablecerContrasena.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRestablecerContrasenaActionPerformed(evt);
            }
        });

        btnIngresar.setText("Ingresar");
        btnIngresar.setMinimumSize(new java.awt.Dimension(110, 39));
        btnIngresar.setName("btnIngresar"); // NOI18N
        btnIngresar.setPreferredSize(new java.awt.Dimension(120, 40));
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/login.png"))); // NOI18N
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jLabel1.setRequestFocusEnabled(false);

        txtUsuario.setName("btnIngresar"); // NOI18N

        lblUsuario.setFont(new java.awt.Font("Tahoma", 1, 12));
        lblUsuario.setText("Usuario");

        lblPassword.setFont(new java.awt.Font("Tahoma", 1, 12));
        lblPassword.setText("Password");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblUsuario)
                            .addComponent(lblPassword))
                        .addGap(27, 27, 27))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
                        .addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(btnIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(btnRestablecerContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblUsuario))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnSalir, 0, 0, Short.MAX_VALUE)
                            .addComponent(btnIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRestablecerContrasena))
                    .addComponent(jLabel1))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        System.exit(0);
}//GEN-LAST:event_btnSalirActionPerformed

    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
        LogUsuarioBL objLogUsuarioBL = new LogUsuarioBL();
        if (!(this.txtUsuario.getText().equals("")) && !(this.txtPassword.getText().equals(""))) {
            try{
                intentos++; // Cantidad de intentos para autenticarse

                String strContrasenhaEncriptada = objEncriptador.encriptar(this.txtPassword.getText());

                AccesoSistemaBL Logicaacceso = new AccesoSistemaBL();
                AccesoSistemaBE objAcceso = new AccesoSistemaBE(txtUsuario.getText(),strContrasenhaEncriptada);
                UsuarioBE objUsuario = new UsuarioBE();
                objUsuario= Logicaacceso.validarCuenta(objAcceso);
                if (objUsuario !=  null){
                    LogUsuarioBE objLogUsuarioBE = new LogUsuarioBE();
                    objLogUsuarioBE.setObjUsuarioBE(objUsuario);

                    boolean registro = objLogUsuarioBL.registrarLog(objLogUsuarioBE);
                    int codlog=objLogUsuarioBL.obtenerIdLog();
                    if (registro){
                       //if(objAcceso.getStrClave().equals(objEncriptador.encriptar(objUsuario.getPassword()))){
                       //if (objAcceso.getStrClave().equals(objUsuario.getPassword())){
                        if(objAcceso.getStrClave().equals(objUsuario.getPassword()) || objUsuario.getPassword().equals("pass")){
                            frmVentanaPrincipal ventana = new frmVentanaPrincipal(objUsuario,codlog);
                            conectado=true;
                            this.setVisible(false);
                            //deshabilita todos los menus
                            setEnableMenus(ventana,false);
                            //habilitar menus permitidos al usario
                            ModuloBL objModuloBL = new ModuloBL();
                            ArrayList<ModuloBE> listaModulo = new ArrayList<ModuloBE>();
                            listaModulo = objModuloBL.getModulo(objUsuario.getCodPerfil());

                            if (listaModulo != null){
                                for (int cont=0;cont<listaModulo.size();cont++){
                                    //System.out.printf("%s\n",listaFuncionalidad.get(cont).getStrNameVentana());
                                    setMenuItem( ventana,listaModulo.get(cont).getModulo());
                                }
                            } else{System.out.printf("No listo las funcionalidadess");}
                            this.txtPassword.setText("");
                            this.txtUsuario.setText("");

                            //muestro la pantalla Principal
                            ventana.setVisible(true);

                        }
                        else{
                            // Falta tunear para saber qe fallo, si el usuario o la contraseña
                            JOptionPane.showMessageDialog(null,"Error en ingreso de datos."," Mensaje ",JOptionPane.ERROR_MESSAGE);
                            this.txtUsuario.setText("");
                            this.txtPassword.setText("");
                            this.txtUsuario.requestFocus();
                        }
                    } else{
                        //verifica el numero de intentos
                        if (intentos == 3 &&  conectado==false){
                            JOptionPane.showMessageDialog(null,"Se excedió el número de intentos máximo"," Mensaje ",JOptionPane.ERROR_MESSAGE);
                            this.dispose();
                            System.exit(0);
                        } else{
                            JOptionPane.showMessageDialog(null,"Nombre o Clave incorrecta"," Mensaje ",JOptionPane.ERROR_MESSAGE);
                            this.txtPassword.setText("");
                            this.txtUsuario.transferFocus();
                        }
                    }
                }

            } catch(Exception exc){
                System.out.printf("ERROR=%s",exc.getMessage());
                JOptionPane.showMessageDialog(null,"Error en Ingreso","Mensaje ",JOptionPane.ERROR_MESSAGE);
            }
        } else{
            JOptionPane.showMessageDialog(null,"Debe Ingresar el nombre del Usuario y la Clave"," Mensaje ",JOptionPane.ERROR_MESSAGE);
            this.btnSalir.transferFocus();
        }

    }//GEN-LAST:event_btnIngresarActionPerformed

    private void btnRestablecerContrasenaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRestablecerContrasenaActionPerformed
        // TODO add your handling code here:
        UsuarioDA objUsuarioDA=new UsuarioDA();
        usr = txtUsuario.getText().toString();
        if (txtUsuario.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Debe ingresar un nombre de usuario","ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        correo_destino = objUsuarioDA.ObtenerCorreo(usr);
        nueva_contrasenha=generadorContrasenha.getPassword(generadorContrasenha.NUMEROS+generadorContrasenha.MINUSCULAS+generadorContrasenha.MAYUSCULAS+generadorContrasenha.ESPECIALES,(9+5)/2);
        try{
            EnvioContrasenha.enviarCorreo(correo_destino, nueva_contrasenha);
        } catch(Exception ex){
            System.out.println("No se pudo modificar la contraseña");
        }
        byte[] byteContrasenhaEncriptada= objEncriptador.getHash(nueva_contrasenha);
        String strContrasenhaEncriptada ="";
        for (int i=0;i<byteContrasenhaEncriptada.length;i++){
            strContrasenhaEncriptada +=byteContrasenhaEncriptada[i];
        }
        objUsuarioDA.ActualizarContrasena(usr,strContrasenhaEncriptada);

    }//GEN-LAST:event_btnRestablecerContrasenaActionPerformed

    
     /**
     * @param args the command line arguments
     */
      
     public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                try
                {
                    // Aplicamos Look and Feel para la GUI
                    UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
                    LiquidLookAndFeel.setLiquidDecorations(true);
                }
                    catch (Exception e)
                {
                    e.printStackTrace();
                }
                
                new frmVentanaAcceso().setVisible(true);
            }
        });
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnIngresar;
    private javax.swing.JButton btnRestablecerContrasena;
    public static javax.swing.JButton btnSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables

    

    private void setEnableMenus(frmVentanaPrincipal form,boolean estado) {
        int cont_menus=0;
        while(cont_menus<form.getJMenuBar().getMenuCount()-1){
            int cont_items=0;
          form.getJMenuBar().getMenu(cont_menus).setEnabled(false);
          cont_menus++;
        }
    }

    // Habilita los menus y submenus segun el perfil del usuario
    private void setMenuItem(frmVentanaPrincipal formulario,String nombre) {

           if (nombre.equals("Documentos"))
                formulario.mnuDocumentos.setEnabled(true);
           else
               if (nombre.equals("Evaluacion"))
                    formulario.mnuEvaluacion.setEnabled(true);
               else
                    if (nombre.equals("Seguridad"))
                        formulario.mnuSeguridad.setEnabled(true);
                    else
                        if (nombre.equals("Auditoria"))
                            formulario.mnuAuditoria.setEnabled(true);
    }

}